import { useMemo } from 'react';
import { FacilityDevice, EnvironmentalSensor } from '../types';

/**
 * 自定义hook：处理环境传感器数据
 * @param facilities 所有设施设备数据
 * @returns 过滤并格式化后的环境传感器数据
 */
export const useEnvironmentalSensors = (
  facilities: FacilityDevice[]
): EnvironmentalSensor[] => {
  const environmentalSensors = useMemo(() => {
    return facilities
      .filter(facility => ['temperature', 'humidity', 'smoke', 'waterLeak', 'airFlow'].includes(facility.type))
      .map(facility => {
        // 类型断言确保我们可以安全访问EnvironmentalSensor特有的属性
        const sensor = facility as EnvironmentalSensor;
        return {
          ...sensor,
          // 确保status字段符合要求
          status: (sensor.status as 'normal' | 'warning' | 'critical') || 'normal',
          // 确保必需的字段都有值
          unit: 'unit' in sensor ? sensor.unit : '',
          value: 'value' in sensor ? sensor.value : 0,
          updateInterval: 'updateInterval' in sensor ? sensor.updateInterval : 30000,
          lastUpdated: 'lastUpdated' in sensor ? sensor.lastUpdated : new Date().toISOString()
        };
      });
  }, [facilities]);

  return environmentalSensors;
};

export default useEnvironmentalSensors;